package verifier;

import builder.SudokuBuilder;
import entity.SudokuGrid;

import java.util.Arrays;

/**
 * Created by kllso on 17-5-3.
 */
public class SudokuVerifier {
    private final static int[] STANDARD_INTS = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
    private SudokuBuilder sudokuBuilder;
    private int testTime = 10000;


    public SudokuVerifier(SudokuBuilder sudokuBuilder) {
        this.sudokuBuilder = sudokuBuilder;
    }

    public long verify() {
        long before = System.currentTimeMillis();
        for (int i = 0; i < testTime; i++) {
            SudokuGrid sudokuGrid = sudokuBuilder.build();
            //行验证
            for (int j = 0; j < 9; j++) {
                int[] row = sudokuGrid.getRow(j);
                if (!uniqueVerify(row)) {
                    return -1;
                }
            }
            //列验证
            for (int j = 0; j < 9; j++) {
                int[] column = sudokuGrid.getColumn(j);
                if (!uniqueVerify(column)) {
                    return -1;
                }
            }
            //宫验证
            for (int j = 0; j < 9; j++) {
                int[][] block = sudokuGrid.getBlock(j);
                if (!uniqueVerify(block)) {
                    return -1;
                }
            }
        }
        long after = System.currentTimeMillis();
        return after - before;
    }

    private boolean uniqueVerify(int[] ints) {
        Arrays.sort(ints);
        return Arrays.equals(ints, STANDARD_INTS);
    }

    private boolean uniqueVerify(int[][] ints) {
        int[] tmp = new int[9];
        int i = 0;
        for (int y = 0; y < 3; y++) {
            for (int x = 0; x < 3; x++) {
                tmp[i++] = ints[x][y];
            }
        }
        return uniqueVerify(tmp);
    }

    public int getTestTime() {
        return testTime;
    }

    public void setTestTime(int testTime) {
        this.testTime = testTime;
    }
}
